package com.bitcat.firstapp.demo.musicdemo

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bitcat.firstapp.databinding.ItemMusicBinding

class MusicAdapter:RecyclerView.Adapter<MusicAdapter.ViewHolder>() {

    private val musicList = mutableListOf<MusicInfo>()




    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemMusicBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int = musicList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(musicList[position])
    }

    inner class ViewHolder(private val binding: ItemMusicBinding):RecyclerView.ViewHolder(binding.root) {
        fun bind(musicInfo: MusicInfo) {
            binding.tvTitle.text = musicInfo.title
            binding.tvArtist.text = musicInfo.artist
            binding.tvDuration.text = formatDuration(musicInfo.duration)

            //点击跳转详情页
            binding.root.setOnClickListener {
                //方式一 直接跳转
//                val intent = Intent(binding.root.context,MusicDetailActivity::class.java)
//                intent.putExtra("music",musicInfo)
//                binding.root.context.startActivity(intent)

                //方式二 接口回调
                if (onItemClickListener != null){
                    onItemClickListener?.onItemClick(musicInfo)
                }
            }
        }


        private fun formatDuration(duration: Long): String {
            val minutes = duration / 1000 / 60
            val seconds = duration / 1000 % 60
            return String.format("%02d:%02d", minutes, seconds)
        }
    }

    fun updateMusicList(musicList: List<MusicInfo>) {
        this.musicList.clear()
        this.musicList.addAll(musicList)
        notifyDataSetChanged()
    }

    interface OnItemClickListener {
        fun onItemClick(musicInfo: MusicInfo)
    }

    private var onItemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(listener: OnItemClickListener) {
        onItemClickListener = listener
    }
}